package com.outsourcing.bottle.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.LoginUserInfoTable;
import com.outsourcing.bottle.domain.LoginUserInfo;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.UICore;
/**
 * 
 * @author 06peng
 *
 */
public class SearchSchoolActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener {

	private EditText editSearchView;
	private EditText editAddView;
	private ImageView searchView;
	private ImageView addView;
	private ListView listView;
	private RelativeLayout searchLayout;
	
	private final int search_school = 1;
	private final int error = 2;
	private final int add_school = 3;
	private Handler handler;
	private List<String> schoolList;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.search_school);
		handler = new Handler(this);
		initWidget();
	}
	
	private void initWidget() {
		editSearchView = (EditText) findViewById(R.id.search_school_edit);
		editSearchView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
					if (editSearchView.getText().toString().trim().equals("")) {
						onToast(getString(R.string.setting_school_search_error));
						return true;
					}
					UICore.eventTask(SearchSchoolActivity.this, SearchSchoolActivity.this, search_school, "search_school", editSearchView.getText().toString().trim());
				}
				return false;
			}
		});
		editAddView = (EditText) findViewById(R.id.setting_school_add_edit);
		editAddView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {

					if (editAddView.getText().toString().trim().equals("")) {
						onToast(getString(R.string.setting_school_search_error));
						return true;
					}
					UICore.eventTask(SearchSchoolActivity.this, SearchSchoolActivity.this, add_school, "add_school", editAddView.getText().toString().trim());
				
				}
				return false;
			}
		});
		searchView = (ImageView) findViewById(R.id.search_school_go);
		searchView.setOnClickListener(this);
		addView = (ImageView) findViewById(R.id.setting_school_add_iamge);
		addView.setOnClickListener(this);
		listView = (ListView) findViewById(R.id.search_school_list);
		searchLayout = (RelativeLayout) findViewById(R.id.search_school_layout);
		if (AppContext.language == 1) {
			searchLayout.setVisibility(View.VISIBLE);
		} else {
			searchLayout.setVisibility(View.GONE);
			listView.setVisibility(View.GONE);
		}
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				String school = schoolList.get(arg2);
				UICore.eventTask(SearchSchoolActivity.this, SearchSchoolActivity.this, add_school, "add_school", school);
			}
		});
	}
	
	public void back(View v) {
		finish();
	}
	
	@Override
	public void onClick(View v) {
		if (v == searchView) {
			if (editSearchView.getText().toString().trim().equals("")) {
				onToast(getString(R.string.setting_school_search_error));
				return;
			}
			UICore.eventTask(this, this, search_school, "search_school", editSearchView.getText().toString().trim());
		} else if (v == addView) {
			if (editAddView.getText().toString().trim().equals("")) {
				onToast(getString(R.string.setting_school_search_error));
				return;
			}
			UICore.eventTask(this, this, add_school, "add_school", editAddView.getText().toString().trim());
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case search_school:
			if (schoolList!=null&&schoolList.size()>0) {
				listView.setVisibility(View.VISIBLE);
				SchoolAdapter adapter = new SchoolAdapter();
				listView.setAdapter(adapter);	
			}
			break;
		case error:
			onToast((String) msg.obj);
			SearchSchoolActivity.this.finish();
			break;
		case add_school:
			onToast((String) msg.obj);
			Intent intent = new Intent(SearchSchoolActivity.this, SettingEducationActivity.class);
			setResult(0,intent);
			SearchSchoolActivity.this.finish();
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case search_school:
			searchSchool();
			break;
		case add_school:
			addSchool((String) obj);
			break;
		default:
			break;
		}
	}
	
	private void searchSchool() {
		String url = UrlConfig.search_school;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("keyword", editSearchView.getText().toString().trim());
		paramsMap.put("page", "1");
		paramsMap.put("count", "20");
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject object = new JSONObject(result);
				JSONObject resultObj = object.getJSONObject("results");
				if (resultObj.getInt("authok") == 0) {
					Message msg = Message.obtain(handler, error, resultObj.getString("errmsg"));
					handler.sendMessage(msg);
				} else {
					JSONArray array = object.getJSONArray("schools_list");
					schoolList = new ArrayList<String>();
					for (int i = 0;i < array.length();i++) {
						JSONObject school = array.getJSONObject(i);
						schoolList.add(school.getString("school"));
					}
					handler.sendEmptyMessage(search_school);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void addSchool(String school) {
		String url = UrlConfig.add_school_info;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("school", school);
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject object = new JSONObject(result);
				JSONObject resultObj = object.getJSONObject("results");
				if (resultObj.getInt("success") == 0) {
					Message msg = Message.obtain(handler, error, resultObj.getString("errmsg"));
					handler.sendMessage(msg);
				} else {
					getLoginUserInfo();
					Message msg = Message.obtain(handler, error, resultObj.getString("successmsg"));
					handler.sendMessage(msg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getLoginUserInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());

		try {
			String result = HttpUtils.doGet(url.toString());
			if (result == null) {
				return;
			}
			Gson gson = new Gson();
			LoginUserInfo loginUserInfo = gson.fromJson(result, LoginUserInfo.class);
			if (loginUserInfo.getResults().getAuthok() == 1) {
				LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable();
				if (null != loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid())) {
					loginUserInfoTable.deleteLoginUserInfoById(AppContext.getInstance().getLogin_uid());
					loginUserInfoTable.saveLoginUserInfo(loginUserInfo
							.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
				} else {
					loginUserInfoTable.saveLoginUserInfo(loginUserInfo
							.getLoginuser_info(), AppContext.getInstance().getLogin_uid());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class SchoolAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return schoolList.size();
		}

		@Override
		public Object getItem(int position) {
			return schoolList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.setting_listitem, null);
			}
			TextView school = (TextView) convertView.findViewById(R.id.setting_listitem_name);
			ImageView add = (ImageView) convertView.findViewById(R.id.setting_listitem_image);
			add.setVisibility(View.GONE);
			String str = schoolList.get(position);
			if (str != null) {
				school.setText(str);
			}
			return convertView;
		}
		
	}
}
